package com.uplift.common.utils;


import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

/**
 * 服务定位器<br/>
 * 1、获取Spring上下文<br/>
 * 2、获取默认数据源<br/>
 * 3、注册、获取、移除Spring Bean
 * 
 * @author bcwang
 *
 */
@Service
public class ServiceLocator implements ApplicationContextAware {
	
	private static final Logger logger = LogManager.getLogger(ServiceLocator.class);

	public static ApplicationContext context;

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		context = arg0;
	}

	/**
	 * 获取Bean
	 * 
	 * @param beanName
	 * @param beanClass
	 * @return T
	 */
	public static <T> Map<String, T> getBeanIgnoreException(Class<T> beanClass) {
		if (context == null) {
			return null;
		}
		try {
			return context.getBeansOfType(beanClass);
		} catch (NoSuchBeanDefinitionException ex) {
			logger.error("【Bean Factory】未找到：" + beanClass);
		}
		return null;
	}

}
